<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 工序物料配置管理
 *
 * @icon fa fa-cogs
 * @remark 管理产品型号的工序物料配置
 */
class ProcessMaterial extends Backend
{
    /**
     * ProcessMaterial模型对象
     * @var \app\admin\model\scanwork\ProcessMaterial
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\ProcessMaterial;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['model.product', 'process', 'material'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取产品型号列表
        $models = \app\admin\model\scanwork\ProductModel::with('product')->select();
        $this->view->assign('models', $models);
        
        // 获取工序列表
        $processes = \app\admin\model\scanwork\Process::where('status', 1)->select();
        $this->view->assign('processes', $processes);
        
        // 获取物料列表
        $materials = \app\admin\model\scanwork\Material::where('status', 1)->select();
        $this->view->assign('materials', $materials);
        
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取产品型号列表
        $models = \app\admin\model\scanwork\ProductModel::with('product')->select();
        $this->view->assign('models', $models);
        
        // 获取工序列表
        $processes = \app\admin\model\scanwork\Process::where('status', 1)->select();
        $this->view->assign('processes', $processes);
        
        // 获取物料列表
        $materials = \app\admin\model\scanwork\Material::where('status', 1)->select();
        $this->view->assign('materials', $materials);
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    $count += $item->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 批量配置工序物料
     */
    public function batchConfig()
    {
        if ($this->request->isPost()) {
            $modelId = $this->request->post('model_id');
            $processMaterials = $this->request->post('process_materials/a', []);
            
            if (!$modelId) {
                $this->error('请选择产品型号');
            }
            
            // 删除该型号的现有配置
            $this->model->where('model_id', $modelId)->delete();
            
            $result = 0;
            Db::startTrans();
            try {
                foreach ($processMaterials as $pm) {
                    if (!empty($pm['process_id']) && !empty($pm['material_id']) && !empty($pm['quantity'])) {
                        $this->model->create([
                            'model_id' => $modelId,
                            'process_id' => $pm['process_id'],
                            'material_id' => $pm['material_id'],
                            'quantity' => $pm['quantity'],
                            'loss_rate' => $pm['loss_rate'] ?: 0,
                            'is_required' => isset($pm['is_required']) ? 1 : 0
                        ]);
                        $result++;
                    }
                }
                Db::commit();
                $this->success("成功配置 {$result} 个工序物料");
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        
        // 获取产品型号列表
        $models = \app\admin\model\scanwork\ProductModel::with('product')->select();
        $this->view->assign('models', $models);
        
        // 获取工序列表
        $processes = \app\admin\model\scanwork\Process::where('status', 1)->select();
        $this->view->assign('processes', $processes);
        
        // 获取物料列表
        $materials = \app\admin\model\scanwork\Material::where('status', 1)->select();
        $this->view->assign('materials', $materials);
        
        return $this->view->fetch();
    }

    /**
     * 获取型号的工序物料配置
     */
    public function getModelProcessMaterials()
    {
        $modelId = $this->request->get('model_id');
        if (!$modelId) {
            $this->error('参数错误');
        }
        
        $processMaterials = $this->model
            ->with(['process', 'material'])
            ->where('model_id', $modelId)
            ->select();
            
        $this->success('', $processMaterials);
    }
}
